package com.jingxuan.controller;

import com.jingxuan.common.annotation.NoAuth;
import com.jingxuan.common.annotation.RequirePermission;
import com.jingxuan.common.result.Result;
import com.jingxuan.dto.request.ProductListRequest;
import com.jingxuan.dto.request.ProductsKeywordSearchRequest;
import com.jingxuan.dto.request.ProductsWeightSearchRequest;
import com.jingxuan.dto.response.ProductStandardizeResponse;
import com.jingxuan.dto.response.ProductsResponse;
import com.jingxuan.dto.response.CompareProductsResponse;
import com.jingxuan.dto.response.SimilarProductsResponse;
import com.jingxuan.dto.request.CompareProductsRequest;
import com.jingxuan.service.ProductsService;
import com.jingxuan.service.ProductsTypeService;

import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequestMapping("/products")
@RequiredArgsConstructor
public class ProductsController {

    @Autowired
    private ProductsService productsService;

    @Autowired
    private ProductsTypeService productsTypeService;

    /**
     * 根据关键词搜索商品
     * GET /products
     */
    @NoAuth
    @GetMapping
    public Result<ProductsResponse> searchProducts(@Valid ProductsKeywordSearchRequest request) {
        log.info("搜索商品，请求参数：keyword={}, platformId={}, page={}, pageSize={}",
                request.getKeyword(), request.getPlatformId(), request.getPage(), request.getPageSize());
        ProductsResponse response = productsService.searchProducts(request);
        return Result.success(response);
    }

    /**
     * 根据关键词和权重搜索商品
     * POST /products/search-with-weights
     */
    @NoAuth
    @PostMapping("/search-with-weights")
    public Result<ProductsResponse> searchProductsWithWeights(@Valid @RequestBody ProductsWeightSearchRequest request) {
        log.info("带权重搜索商品，请求参数：keyword={}, priceWeight={}, reputationWeight={}, heatWeight={}, timelinessWeight={}",
                request.getKeyword(), request.getPriceWeight(), request.getReputationWeight(),
                request.getHeatWeight(), request.getTimelinessWeight());
        ProductsResponse response = productsService.searchProductsWithWeights(request);
        return Result.success(response);
    }

    /**
     * 获取商品详情
     * GET /products/{productId}
     */
    @NoAuth
    @GetMapping("/{productId}")
    public Result<com.jingxuan.dto.response.ProductResponse> getProductDetail(@PathVariable String productId) {
        log.info("获取商品详情，请求参数：productId={}", productId);
        com.jingxuan.dto.response.ProductResponse response = productsService.getProductDetail(productId);
        return Result.success(response);
    }

    /**
     * 获取相似商品
     * GET /products/{productId}/similar
     */
    @GetMapping("/{productId}/similar")
    public Result<SimilarProductsResponse> getSimilarProducts(@PathVariable String productId,
                                                              @RequestParam(value = "limit", required = false) Integer limit) {
        log.info("获取相似商品，请求参数：productId={}, limit={}", productId, limit);
        SimilarProductsResponse response = productsService.getSimilarProducts(productId, limit);
        return Result.success(response);
    }
    
    /**
     * 商品比价接口，支持上传用户偏好数据提升排名准确性
     * POST /products/compare
     */
    @PostMapping("/compare")
    public Result<CompareProductsResponse> compareProducts(@Valid @RequestBody CompareProductsRequest request) {
        log.info("执行商品比价，productIds={}, userId={}, preferenceTags={}, behaviorCount={}",
                request.getProductIds(),
                request.getUserId(),
                request.getPreferenceTags(),
                request.getUserBehaviors() == null ? 0 : request.getUserBehaviors().size());
        CompareProductsResponse response = productsService.compareProducts(request);
        return Result.success(response);
    }


    /**
     * 获取所有商品类型
     * GET /products/types
     */
    @NoAuth
    @GetMapping("/types")
    public Result<Set<String>> getAllProductTypes() {
        log.info("获取所有商品类型");
        Set<String> types = productsTypeService.getAllProductTypes();
        return Result.success( "获取所有商品类型成功", types);
    }

    // TODO: 管理员对于商品的操作，需要权限注解


    /**
     * 新增商品
     * POST /products
     */
    @RequirePermission("product:manage")
    @PostMapping
    public Result<com.jingxuan.dto.response.ProductResponse> addProduct(@Valid @RequestBody com.jingxuan.dto.request.ProductSaveRequest request) {
        log.info("新增商品：{}", request.getProductName());
        com.jingxuan.dto.response.ProductResponse response = productsService.addProduct(request);
        return Result.success("新增商品成功", response);
    }

    /**
     * 修改商品
     * PUT /products/{productId}
     */
    @RequirePermission("product:manage")
    @PutMapping("/{productId}")
    public Result<com.jingxuan.dto.response.ProductResponse> updateProduct(@PathVariable String productId,
                                                                           @Valid @RequestBody com.jingxuan.dto.request.ProductSaveRequest request) {
        log.info("修改商品：{}", productId);
        com.jingxuan.dto.response.ProductResponse response = productsService.updateProduct(productId, request);
        return Result.success("修改商品成功", response);
    }

    /**
     * 删除商品
     * DELETE /products/{productId}
     */
    @RequirePermission("product:manage")
    @org.springframework.web.bind.annotation.DeleteMapping("/{productId}")
    public Result<Void> deleteProduct(@PathVariable String productId) {
        log.info("删除商品：{}", productId);
        productsService.deleteProduct(productId);
        return Result.success("删除商品成功", null);
    }

    /**
     * 商品数据标准化
     * PUT /products/{productId}/standardize
     */
    @RequirePermission("product:manage")
    @PutMapping("/{productId}/standardize")
    public Result<ProductStandardizeResponse> standardizeProduct(@PathVariable String productId) {
        log.info("执行商品数据标准化，productId={}", productId);
        ProductStandardizeResponse response = productsService.standardizeProduct(productId);
        return Result.success("商品数据已标准化", response);
    }

    /**
     * 管理端商品列表
     */
    @RequirePermission("product:manage")
    @GetMapping("/admin/list")
    public Result<ProductsResponse> listProducts(ProductListRequest request) {
        log.info("管理端查询商品列表, keyword={}", request == null ? null : request.getKeyword());
        ProductsResponse response = productsService.listProducts(request);
        return Result.success(response);
    }
    
}
